package com.free4k.hss;

import com.free4k.hss.entity.PoemArticle;
import com.free4k.hss.service.PoemArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.swing.*;
import java.awt.*;
import java.util.List;


@Component
public class Hsswing {

    @Autowired
    PoemArticleService poemArticleService;

    @PostConstruct
    public void init() {

        SwingUtilities.invokeLater(() -> {

            JFrame frame = new JFrame("Spring Boot + Swing");

//            frame.setSize(800, 600);
//            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.setLocation(200,100);

            JPanel panel = new JPanel();

            JTextArea textArea = new JTextArea(32,68);
            JScrollPane scrollPane = new JScrollPane(textArea);

            JLabel label = new JLabel("根据姓名查询:");
            JTextField textField = new JTextField(10);
            label.setLabelFor(textField);

            JButton button = new JButton("查询");
            button.addActionListener(e -> {

                List<PoemArticle> list;
                String text = textField.getText();

                if (text == null || text.length() == 0)
                    list = poemArticleService.list();
                else
                    list = poemArticleService.selectLikeName(text);

                StringBuilder stringBuilder = new StringBuilder();

                for (PoemArticle poemArticle : list) {
                    stringBuilder.append(poemArticle.toString()).append("\n");
                }
                if (stringBuilder.length() == 0)
                    textArea.setText("没有匹配的数据!!!");
                else
                    textArea.setText(stringBuilder.toString());
            });

            JPanel north = new JPanel();
            north.add(label);
            north.add(textField);
            north.add(button);
            panel.add(scrollPane);
            frame.add(north,BorderLayout.NORTH);
            frame.add(panel,BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);

        });
    }

}
